import * as Fiber from 'fiber';
const axios = Fiber.http.Provider;
const instance = axios.create({
  timeout: 30000
});
// 请求拦截
instance.interceptors.request.use(
  (config) => config,
  (err) => Promise.reject(err)
);
// 响应拦截
instance.interceptors.response.use(
  (res) => {
    const { status, data } = res;
    if (status === 200) {
      return Promise.resolve([data, null]);
    } else {
      return Promise.reject([null, data]);
    }
  },
  (err) => {
    return Promise.reject([null, err]);
  }
);
export default function ajax({ method, url, headers, data }) {
  return new Promise((resolve, reject) => {
    let promise;
    let axiosConfig = {
      method: method, // 请求方法
      url, // 服务器地址
      headers: {
        Accept: 'application/json', // 接受返回数据的类型
        'Content-Type': 'application/json; charset=utf-8', // 内容格式
        ...(headers || {})
      },
      responseType: 'json' // 返回值类型
    };
    if (data) {
      if (method === 'get') {
        axiosConfig.params = data;
      } else if (data instanceof FormData) {
        axiosConfig.data = data;
      } else {
        axiosConfig.data = data;
      }
    }
    promise = instance.request(axiosConfig);
    promise.then(
      (res) => {
        resolve(res);
      },
      (err) => {
        reject(err);
      }
    );
  });
}
